package server.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import server.demo.dto.ApiResponse;
import server.demo.entity.RentalOrder;
import server.demo.service.RentalOrderService;

import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/v1/orders")
public class RentalOrderController {
    
    @Autowired
    private RentalOrderService rentalOrderService;
    
    @GetMapping
    public ResponseEntity<ApiResponse<List<RentalOrder>>> getAllOrders() {
        try {
            List<RentalOrder> orders = rentalOrderService.getAllOrders();
            return ResponseEntity.ok(ApiResponse.success(orders));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("获取订单列表失败：" + e.getMessage()));
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<RentalOrder>> getOrderById(@PathVariable Long id) {
        try {
            Optional<RentalOrder> order = rentalOrderService.getOrderById(id);
            if (order.isPresent()) {
                return ResponseEntity.ok(ApiResponse.success(order.get()));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("获取订单详情失败：" + e.getMessage()));
        }
    }
    
    @GetMapping("/my-rentals")
    public ResponseEntity<ApiResponse<List<RentalOrder>>> getCurrentUserOrders(HttpSession session) {
        try {
            Long currentUserId = (Long) session.getAttribute("userId");
            
            // 验证是否已登录
            if (currentUserId == null) {
                return ResponseEntity.status(401)
                    .body(ApiResponse.error("用户未登录"));
            }
            
            List<RentalOrder> orders = rentalOrderService.getOrdersByUserId(currentUserId);
            return ResponseEntity.ok(ApiResponse.success(orders));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("获取我的租赁记录失败：" + e.getMessage()));
        }
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<ApiResponse<List<RentalOrder>>> getOrdersByUserId(
            @PathVariable Long userId, HttpSession session) {
        try {
            Long currentUserId = (Long) session.getAttribute("userId");
            String userRole = (String) session.getAttribute("userRole");
            
            // 验证是否已登录
            if (currentUserId == null) {
                return ResponseEntity.status(401)
                    .body(ApiResponse.error("用户未登录"));
            }
            
            // 普通用户只能查看自己的订单，管理员可以查看任何用户的订单
            if (!"ADMIN".equals(userRole) && !currentUserId.equals(userId)) {
                return ResponseEntity.status(403)
                    .body(ApiResponse.error("权限不足，只能查看自己的订单"));
            }
            
            List<RentalOrder> orders = rentalOrderService.getOrdersByUserId(userId);
            return ResponseEntity.ok(ApiResponse.success(orders));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("获取用户订单失败：" + e.getMessage()));
        }
    }
    
    @PostMapping
    public ResponseEntity<ApiResponse<RentalOrder>> createOrder(@Valid @RequestBody RentalOrder order, HttpSession session) {
        try {
            Long currentUserId = (Long) session.getAttribute("userId");
            
            // 验证是否已登录
            if (currentUserId == null) {
                return ResponseEntity.status(401)
                    .body(ApiResponse.error("用户未登录"));
            }
            
            // 设置正确的用户ID（从session中获取，不信任前端传来的用户ID）
            order.setUserId(currentUserId);
            
            RentalOrder savedOrder = rentalOrderService.createOrder(order);
            return ResponseEntity.ok(ApiResponse.success(savedOrder));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("创建订单失败：" + e.getMessage()));
        }
    }
    
    @PutMapping("/{id}/approve")
    public ResponseEntity<ApiResponse<RentalOrder>> approveOrder(@PathVariable Long id) {
        try {
            RentalOrder updatedOrder = rentalOrderService.approveOrder(id);
            return ResponseEntity.ok(ApiResponse.success(updatedOrder));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("审批订单失败：" + e.getMessage()));
        }
    }
    
    @PutMapping("/{id}/return")
    public ResponseEntity<ApiResponse<RentalOrder>> returnEquipment(@PathVariable Long id) {
        try {
            RentalOrder updatedOrder = rentalOrderService.returnEquipment(id);
            return ResponseEntity.ok(ApiResponse.success(updatedOrder));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("归还设备失败：" + e.getMessage()));
        }
    }
    
    @GetMapping("/statistics")
    public ResponseEntity<ApiResponse<Map<String, Long>>> getOrderStatistics() {
        try {
            Map<String, Long> statistics = new HashMap<>();
            statistics.put("pending", rentalOrderService.getOrderCountByStatus(RentalOrder.OrderStatus.PENDING));
            statistics.put("active", rentalOrderService.getOrderCountByStatus(RentalOrder.OrderStatus.ACTIVE));
            statistics.put("completed", rentalOrderService.getOrderCountByStatus(RentalOrder.OrderStatus.COMPLETED));
            statistics.put("cancelled", rentalOrderService.getOrderCountByStatus(RentalOrder.OrderStatus.CANCELLED));
            statistics.put("overdue", rentalOrderService.getOrderCountByStatus(RentalOrder.OrderStatus.OVERDUE));
            return ResponseEntity.ok(ApiResponse.success(statistics));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("获取订单统计失败：" + e.getMessage()));
        }
    }
}